package org.jeecg.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.env.Environment;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * 查询Bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        log.info("获取{}类型的bean", clazz.getName());
        return clazz == null ? null : applicationContext.getBean(clazz);
    }

    /**
     * 获取指定Class的Bean, 忽略空
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBeanIgnoreNull(Class<T> clazz) {
        return null == clazz || null == applicationContext ? null : applicationContext.getBean(clazz);
    }

    /**
     * 根据Bean名称获取Bean
     * @param beanName
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        if(StringUtils.isNotBlank(beanName)) {
            return clazz == null ? null : applicationContext.getBean(beanName, clazz);
        }
        return null;
    }

    /**
     * 获取包含某个注解的Bean
     * @param annotationClass
     * @return
     */
    public static List<Class<?>> getBeanWithAnnotation(Class<? extends Annotation> annotationClass) {
        String[] classNames = applicationContext.getBeanNamesForAnnotation(annotationClass);
        for(String str: classNames) {
            System.out.println(str);
        }
        return new ArrayList<>();
    }

    /**
     * 获取SpringBoot环境下的配置
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getPropertyValue(String key, String defaultValue) {
        // 获取
        Environment env = getBean(Environment.class);
        if (env == null) {
            return defaultValue;
        }
        return env.getProperty(key, defaultValue);
    }

    /**
     *  触发自定义的事件
     * @param event
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        try {
            applicationContext.publishEvent(event);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

}
